<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mmod_overtime extends MYAD_Model{
	protected $table_name = 'm_overtimeregistration';
        protected $table_employee = 'm_employee';
        function __construct(){
            parent::__construct();
	}
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    Get all data for view of Leave registration list
     * @Input :         $page = 0;
     * @Output :        (Array) data for view data
     */        
        function getAllData($page = 0){
            $arrayData = array();
            $arraySearch = array(); 
            if(isset($_POST['txtKeyword'])&& $_POST['txtKeyword']!=''){
                $arrayData = array(
                  'b.EmployeeName'    => dQuotes($this->input->post('txtKeyword')),
                );
                $arraySearch =  array(
                    'txtKeyword'=> dQuotes($this->input->post('txtKeyword')),
                );
            }
            $allOvertime = $this->getOverTimeData($arrayData);
            /* load pagination */
            $pagiData = array(
                'base_url'      => base_url('overtime/'),
                'total_rows'    => count($allOvertime['data']),
            );
            $pagination = $this->config->item('pagination');
            $offset = isset($pagiData['per_page']) ? $pagiData['per_page'] : $pagination['per_page'];
            $pagi = $this->getPagination($pagiData);
            $data = array(
                'show' => 'index',
                'js'    =>array('jquery-ui.js'),
                'css'    =>array('jquery-ui.css'),
                'pagi' => $pagi,
                'order' => $page,
                'title' => $this->lang->line('OVT_title'),
            );            
            /* load overtime */
            $OvertimeData = $this->getOverTimeData($arrayData,$page, $offset);
            return array_merge($data,$OvertimeData,$arraySearch);            
        }
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    Insert datas
     * @Input :         
     * @Output :        Return array
     */        
        function insertOvertimeData(){
            $temp =array();
            $data = array(
                'EmployeeId'        => $this->input->post('hidEmployeeId'),
                'StartDate'         => $this->input->post('txtStartDate'),
                'EndDate'           => $this->input->post('txtEndDate'),
                'StartTime'         => $this->input->post('txtStartTime'),
                'EndTime'           => $this->input->post('txtEndTime'),
                'ReasonOfOvertime'  => dQuotes($this->input->post('txtReasonOfOvertime')),               
            );
            $dataCondition = $data;
            $dataCondition['OvertimeRegistrationId'] = 0;
            $result = $this->duplicateDateTime($dataCondition);
            if ($result) {
                $temp['flag'] = FALSE;
                $temp['message'] = $this->lang->line('OVT_updateDB_duplicate');
                return $temp;
            }       
            $result = $this->updateDB($this->table_name,$data);
            if($result == TRUE){
                $temp['flag'] = TRUE;
                $temp['message'] = $this->lang->line('OVT_updateDB_success');                   
            }
            else{
                $temp['flag'] = FALSE;
                $temp['message'] = $this->lang->line('OVT_updateDB_fall');
            }                
            return $temp;           
        }
    /*
     * @author :        Hunglv
     * @created:        
     * @Description:    add Leave registration Data
     * @Input :         
     * @Output :        
     */        
        function updateOvertime(){
            $temp =array();
            $data = array(
                'EmployeeId'        => $this->input->post('hidEmployeeId'),
                'StartDate'         => $this->input->post('txtStartDate'),
                'EndDate'           => $this->input->post('txtEndDate'),
                'StartTime'         => $this->input->post('txtStartTime'),
                'EndTime'           => $this->input->post('txtEndTime'),
                'ReasonOfOvertime'  => dQuotes($this->input->post('txtReasonOfOvertime')),
                'Del_Flag'          => $this->input->post('chkDelFlag'),
            );
            $id = $this->input->post('hidOvertimeId');
            $dataCondition = $data;
            $dataCondition['OvertimeRegistrationId'] = $id;
            $result = $this->duplicateDateTime($dataCondition);
            if ($result) {
                $temp['flag'] = FALSE;
                $temp['data'] = $data;
                $temp['message'] = $this->lang->line('OVT_updateDB_duplicate');
                return $temp;
            }                      
            $result = $this->updateDB($this->table_name,$data,array("OvertimeRegistrationId"=>$id));
            if($result == TRUE){
                $temp['flag'] = TRUE;
                $temp['message'] = $this->lang->line('LR_updateDB_success');                   
            }
            else{
                $temp['flag'] = FALSE;
                $temp['message'] = $this->lang->line('LR_updateDB_fall');
            }                
            return $temp;
        }          
        /*
         * @author :        HungLV
         * @Description:    Get Overtime data
         * @Input :         
         *                  (Integer) $limit
         *                  (Integer) $offset
         * @Output :        Array data
         */       
        function getOverTimeData($arrayData,$limit = Null, $offset = Null){                       
            $this->db->from($this->table_name.' as a ');
            $this->db->join($this->table_employee.' as b ', 'b.EmployeeId = a.EmployeeId');
            $this->db->select('a.OvertimeRegistrationId,a.EmployeeId,a.StartDate,a.EndDate,a.StartTime,a.EndTime,a.ReasonOfOvertime,a.Del_Flag,b.EmployeeName');
            $this->db->where('b.CompanyCode',$this->session->userdata('CompanyCode'));
            if(count($arrayData)){
                $this->db->like($arrayData);
            }             
            if ($limit !== Null && $offset !== Null) {
                $this->db->limit($offset, $limit);
            } elseif ($limit !== NULL) {
                $this->db->limit($limit);
            }
            $query = $this->db->get();
            $result = $query->result_array();
            return array('data' => $result);
        }
        /*
         * @author :        HungLV
         * @Description:    Get All employee
         * @Input :         
         *                  $EmployeeId = 0
         * @Output :        Array data
         */       
        function allEmployee($page){
            // create session data
            $this->session->set_userdata('txtStartDate', $this->input->post('txtStartDate'));
            $this->session->set_userdata('txtEndDate', $this->input->post('txtEndDate'));
            $this->session->set_userdata('txtStartTime', $this->input->post('txtStartTime'));
            $this->session->set_userdata('txtEndTime', $this->input->post('txtEndTime'));     
            $this->session->set_userdata('txtReasonOfOvertime', $this->input->post('txtReasonOfOvertime'));     
            // config pagination
            $employeeData = $this->loadDataEmployee();
            /* load pagination */
            $pagiData = array(
                'base_url' => base_url('overtime/listemployee'),
                'total_rows' => count($employeeData['data']),
                'uri_segment' => 3,
            );
            $pagination = $this->config->item('pagination');
            $offset = isset($pagiData['per_page']) ? $pagiData['per_page'] : $pagination['per_page'];
            $pagi = $this->getPagination($pagiData);
            $temp = array(
                'overtimeID'=>$this->input->post('hidOvertimeId'),
                'segment'=>$this->input->post('hidSegment'),
                'employeeId'=>$this->input->post('hidEmployeeId'),
                'pagi' => $pagi,
                'order' => $page,
                'show' => 'searchlistemployee',
                'title' => $this->lang->line('LR_SearchList'),
            );

            $data = $this->loadDataEmployee($page, $offset);
            return array_merge($data, $temp);  
        }
        /*
         * @author :        HungLV
         * @Description:    get all data employee
         * @Input :         
         * @Output :        Return Array data
         */       
        function loadDataEmployee($limit = Null, $offset = Null){
            $this->db->select('EmployeeId,EmployeeName,DateOfBirth,IdCardNumber,Email');
            $this->db->where('CompanyCode',$this->session->userdata('CompanyCode'));
            if ($limit !== Null && $offset !== Null) {
                $this->db->limit($offset, $limit);
            } elseif ($limit !== NULL) {
                $this->db->limit($limit);
            }        
            $query = $this->db->get($this->table_employee);
            $result = $query->result_array();
            return array('data' => $result);
        }
        /*
         * @author :        HungLV
         * @Description:    get all id employee by name
         * @Input :         $employeeID
         * @Output :        Return Array data
         */

        function loadEmployeeId($employeeID) {
            $this->db->from($this->table_employee.' as a ');
            $this->db->like('a.EmployeeId', $employeeID);
            $this->db->like('a.CompanyCode',$this->session->userdata('CompanyCode'));
            $query = $this->db->get();
            return $query->row_array();
        }
        /*
         * @author :        HungLV
         * @Description:    get all data by id
         * @Input :         $name = ""
         * @Output :        Return Array data for view
         */ 
        function getOverTimeByID($OvertimeRegistrationId){
            $this->db->from($this->table_name.' as a ');
            $this->db->join($this->table_employee.' as b ', 'b.EmployeeId = a.EmployeeId');
            $this->db->select('a.OvertimeRegistrationId,a.EmployeeId,a.StartDate,a.EndDate,a.StartTime,a.EndTime,a.ReasonOfOvertime,a.Del_Flag,b.EmployeeName');
            $this->db->where('OvertimeRegistrationId',$OvertimeRegistrationId);
            $this->db->where('b.CompanyCode',$this->session->userdata('CompanyCode'));
            $query = $this->db->get();
            return $query->row_array();
        }
        /*
         * @author :        HungLV
         * @Description:    Validate data input
         * @Input :         Null
         * @Output :        
         */ 
        function validateData(){
            $_POST['txtEmployee'] = mb_convert_kana($_POST['txtEmployee'], 'a');
            $_POST['txtStartDate'] = mb_convert_kana($_POST['txtStartDate'], 'a');           
            $_POST['txtEndDate'] = mb_convert_kana($_POST['txtEndDate'], 'a');           
            $_POST['txtStartTime'] = mb_convert_kana($_POST['txtStartTime'], 'a');           
            $_POST['txtEndTime'] = mb_convert_kana($_POST['txtEndTime'], 'a');           
            $this->form_validation->set_error_delimiters('', '');
            $this->form_validation->set_rules('txtEmployee',$this->lang->line('OVT_Employee'),'required'); 
            $this->form_validation->set_rules('txtStartDate', $this->lang->line('LR_StartDate'), 'required|callback_validate_date');
            $this->form_validation->set_rules('txtEndDate', $this->lang->line('LR_EndDate'), 'required|callback_validate_date|callback_lessThanOrEqualDate[txtStartDate]');
            $this->form_validation->set_rules('txtStartTime', $this->lang->line('LR_StartTime'), 'required|callback_validate_time');
            $this->form_validation->set_rules('txtEndTime', $this->lang->line('LR_EndTime'), 'required|callback_validate_time|callback_validate_timeend[txtStartTime]');
            $this->form_validation->set_rules('txtReasonOfOvertime',$this->lang->line('OVT_ReasonOfOvertime'), 'max_length[255]');
            return $this->form_validation->run();
        }
        /*
         * @author :        HungLV
         * @Description:    get setup info for view
         * @Input :         Null
         * @Output :        Return Array for view
         */ 
        function getInfoOvertime(){
            $data = array(
                'title' =>$this->lang->line('OVT_OvertimeRegistration'),
                'js' =>array('jquery-ui.js'),
                'css' =>array('jquery-ui.css'),
                'show' =>'addovertime',
            );
            if (isset($_POST['btnSubmit'])) {
                /* is load default */
                $emp = array(
                    'txtEmployee' => $this->input->post('txtEmployee'),                        
                    'txtStartDate' => $this->input->post('txtStartDate'),             
                    'txtEndDate' => $this->input->post('txtEndDate'),             
                    'txtStartTime' => $this->input->post('txtStartTime'),            
                    'txtEndTime' => $this->input->post('txtEndTime'),
                    'txtReasonOfOvertime' => $this->input->post('txtReasonOfOvertime'),
                );
            } else {
                $emp = array(
                    'txtEmployee' => set_value('txtEmployee'),                     
                    'txtStartDate' => $this->session->userdata('txtStartDate')?$this->session->userdata('txtStartDate'):set_value('txtStartDate'),         
                    'txtEndDate' => $this->session->userdata('txtEndDate')?$this->session->userdata('txtEndDate'):set_value('txtEndDate'),         
                    'txtStartTime' => $this->session->userdata('txtStartTime')?$this->session->userdata('txtStartTime'):set_value('txtStartTime'),         
                    'txtEndTime' => $this->session->userdata('txtEndTime')?$this->session->userdata('txtEndTime'):set_value('txtEndTime'),
                    'txtReasonOfOvertime' => $this->session->userdata('txtReasonOfOvertime')?$this->session->userdata('txtReasonOfOvertime'):set_value('txtReasonOfOvertime'),
                );
            }
            return array_merge($data,$emp);
        }
        /*
         * @author :        HungLV
         * @Description:    get setup info for view
         * @Input :         Null
         * @Output :        Return Array for view
         */ 
        function getInfoEditOvertime($overtime,$employeeID){
            $data = array(
                'title' =>$this->lang->line('OVT_OvertimeRegistration'),
                'js' =>array('jquery-ui.js'),
                'css' =>array('jquery-ui.css'),
                'show' =>'editovertime',
            );
            if (isset($_POST['btnSubmit'])) {
                /* is load default */
                $emp = array(
                    'txtEmployee' => $this->input->post('txtEmployee'),
                    'employeeId' => $this->input->post('hidEmployeeId'),
                    'overtimeID'    => $this->input->post('hidOvertimeId'),
                    'txtStartDate'      => $this->input->post('txtStartDate'),             
                    'txtEndDate'        => $this->input->post('txtEndDate'),             
                    'txtStartTime'      => $this->input->post('txtStartTime'),            
                    'txtEndTime'        => $this->input->post('txtEndTime'),                    
                    'chkDelFlag'        => $this->input->post('chkDelFlag'), 
                    'txtReasonOfOvertime' => $this->input->post('txtReasonOfOvertime'),                
                );
            }
            else{
                if(count($overtime)>0){
                    $employeeInfo = $this->getInfoEmployeeID($employeeID);
                    $emp = array(
                        'txtEmployee' => $employeeInfo['EmployeeName'],       
                        'employeeId' => $employeeInfo['EmployeeId'],       
                        'overtimeID' => $overtime['OvertimeRegistrationId'],
                        'txtStartDate' => $this->session->userdata('txtStartDate')?$this->session->userdata('txtStartDate'):date('Y/m/d',strtotime($overtime['StartDate'])),         
                        'txtEndDate' => $this->session->userdata('txtEndDate')?$this->session->userdata('txtEndDate'):date('Y/m/d',strtotime($overtime['EndDate'])),         
                        'txtStartTime' => $this->session->userdata('txtStartTime')?$this->session->userdata('txtStartTime'):date('G:i',strtotime($overtime['StartTime'])),         
                        'txtEndTime' => $this->session->userdata('txtEndTime')?$this->session->userdata('txtEndTime'):date('G:i',strtotime($overtime['EndTime'])),                           
                        'chkDelFlag' => $this->session->userdata('chkDelFlag')!=''?$this->session->userdata('chkDelFlag'):$overtime['Del_Flag'],         
                        'txtReasonOfOvertime' => $this->session->userdata('txtReasonOfOvertime')?$this->session->userdata('txtReasonOfOvertime'):$overtime['ReasonOfOvertime'],
                    );                               
                }
                else {
                    $emp = array(
                        'txtEmployee' => set_value('txtEmployee'),    
                        'employeeId' => $this->input->post('hidEmployeeId'),
                        'overtimeID'    => $this->input->post('hidOvertimeId'),
                        'txtStartDate' => $this->session->userdata('txtStartDate')?$this->session->userdata('txtStartDate'):set_value('txtStartDate'),         
                        'txtEndDate' => $this->session->userdata('txtEndDate')?$this->session->userdata('txtEndDate'):set_value('txtEndDate'),         
                        'txtStartTime' => $this->session->userdata('txtStartTime')?$this->session->userdata('txtStartTime'):set_value('txtStartTime'),         
                        'txtEndTime' => $this->session->userdata('txtEndTime')?$this->session->userdata('txtEndTime'):set_value('txtEndTime'),
                        'chkDelFlag' => $this->session->userdata('chkDelFlag')!=''?$this->session->userdata('chkDelFlag'):$this->input->post('chkDelFlag'),         
                        'txtReasonOfOvertime' => $this->session->userdata('txtReasonOfOvertime')?$this->session->userdata('txtReasonOfOvertime'):set_value('txtReasonOfOvertime'),                          
                    );
                }             
            }        
            return array_merge($data,$emp);            
        } 
        /*
         * @author :        HungLV
         * @Description:    get data when click button submit
         * @Input :         Null
         * @Output :        Return Array for view
         */ 
        function getDataSubmit(){
            $data = array(
                'EmployeeId'                => $this->input->post('idEmployee'),
                'RegistrationDate'          => $this->input->post('txtDate'),
                'ReasonOfOvertime'          => $this->input->post('txtReasonOfOvertime'),
            );
            return $data;
        }         
        /*
         * @author :        HungLV
         * @Description:    check exist id overtime
         * @Input :         (Number) $id
         * @Output :        Return true or false
         */ 
        function checkIdOvertime($id){
            $this->db->where('OvertimeRegistrationId',$id);
            $query = $this->db->get($this->table_name);
            if($query->num_rows()>0){
                return TRUE;
            }
            else{
                return FALSE;
            }
        }
        /*
         * @author :        HungLV
         * @Description:    return employee info by id
         * @Input :         $idemployee
         * @Output :        Return array
         */
        /*
         * @author :        HungLV
         * @Description:    check exist employee id 
         * @Input :         (Number) $id
         * @Output :        Return true or false
         */

        function checkEmployeeId($id) {
            $this->db->where('EmployeeId', $id);
            $this->db->where('CompanyCode', $this->session->userdata('CompanyCode'));
            $query = $this->db->get($this->table_employee);
            if ($query->num_rows() > 0) {
                return TRUE;
            } else {
                return FALSE;
            }
        }
        function getInfoEmployeeID($idemployee) {
            $this->db->where('EmployeeId',$idemployee);
            $query = $this->db->get($this->table_employee);
            return $query->row_array();
        }        
        /*
         * @author :        HungLV
         * @Description:    check dulicate
         * @Input :         (Number) $id
         * @Output :        Return true or false
         */ 
        function checkDuplicateData($date,$employeeID,$id=''){
            $this->db->where('RegistrationDate',$date);
            $this->db->where('EmployeeId',$employeeID);
            $this->db->where('Del_Flag',0);
            $query = $this->db->get($this->table_name);
            if($query->num_rows()>0){
                $result = $query->result_array();
                if($id!=''){
                    foreach ($result as $value) {
                        if($id!=$value['OvertimeRegistrationId']){
                            return FALSE;
                        }
                    }
                    return TRUE;
                }
                else{
                    return FALSE;
                }
            }
            else{
                return TRUE;
            }
        }
        /*
         * @author :        HungLV
         * @Description:    Unset sesion data
         * @Input :         Null
         * @Output :        Null
         */

        function unsetDataSession() {
            $this->session->unset_userdata('txtStartDate');
            $this->session->unset_userdata('txtEndDate');
            $this->session->unset_userdata('txtStartTime');
            $this->session->unset_userdata('txtEndTime');
            $this->session->unset_userdata('txtReasonOfOvertime'); 
        }
        /*
         * @copyright :     Ienter asia Technologies
         * @author :        Hunglv
         * @version         
         * @created         
         * @Description :   return true if duplicate
         */

        function duplicateDateTime($data = array()) {
            $temp = FALSE;
            if (count($data)) {
                $overtimeId = isset($data['OvertimeRegistrationId']) ? $data['OvertimeRegistrationId'] : 0;
                $employeeId = isset($data['EmployeeId']) ? $data['EmployeeId'] : 0;
                //set start time --> end time
                $startDate = strtotime($data['StartDate'] . ' ' . $data['StartTime'] . ':00');
                $endDate = strtotime($data['EndDate'] . ' ' . $data['EndTime'] . ':00');
                if ($overtimeId) {
                    //is update
                    $condition = array(
                        'OvertimeRegistrationId !=' => (integer) $overtimeId,
                        'EmployeeId' => (integer) $employeeId,
                        'Del_Flag' => 0,
                    );
                } else {
                    // is insert
                    $condition = array(
                        'EmployeeId' => (integer) $employeeId,
                        'Del_Flag' => 0,
                    );
                }
                $query = $this->db->get_where($this->table_name, $condition);
                $result = $query->result();
                if (count($result)) {
                    foreach ($result as $item) {
                        $tempStart = strtotime($item->StartDate . ' ' . $item->StartTime);
                        $tempEnd = strtotime($item->EndDate . ' ' . $item->EndTime);
                        if (!($endDate <= $tempStart || $startDate >= $tempEnd)) {
                            $temp = TRUE;
                            break;
                        }
                    }
                }
            }
            return $temp;
        }        
}
?>